import { cloneDeep } from 'lodash-es'

export const keymap = {
  // 历史文献专属子目区信息
  ZM: {
    BMLSWX050: 'subitemTitle', // 子目正题名
    BMLSWX051: 'volumeName', // 分册名
    BMLSWX052: 'subItemFirstResponsible', // 子目第一责任者
    BMLSWX053: 'subtopicVersionDescription', // 子目版本说明
    BMLSWX054: 'subitemCollectionCode', // 子目馆藏码
    flag: 'flag'
  },
  // 历史文献专属责任者区信息
  ZRZ: {
    BMLSWX011: 'countryOrDynastyOfResponsibility', // 责任者国别或朝代
    BMLSWX012: 'nameOfResponsiblePerson', // 责任者名称
    BMLSWX013: 'responsibilityMode', // 责任方式
    flag: 'flag'
  }
}

// 表单数据格式化为接口数据
export const formatedData = (key: string, data: any) => {
  if (!data) return []
  data = cloneDeep(data)

  const result = [] as any[]
  // @ts-ignore
  const zmKeymap = keymap[key]

  const originData = data[key] || []
  for (let i = 0; i < originData.length; i++) {
    const item = originData[i]
    const zm = {} as any
    Object.keys(zmKeymap).forEach((key: string) => {
      if (item[key] || item[key] == 0) {
        // @ts-ignore
        zm[zmKeymap[key]] = item[key]
      }

      delete item[key]
    })
    if (Object.keys(zm).length) {
      result.push({
        ...zm,
        ...item
      })
    }
  }
  return result
}

// 接口数据格式化为表单数据
const formatedDataToForm = (key: string, data: any) => {
  if (!data) return []
  data = cloneDeep(data)
  const result = {} as any
  // @ts-ignore
  const zmKeymap = keymap[key]

  const list = [] as any[]
  for (let i = 0; i < data.length; i++) {
    const item = data[i]
    const zm = {} as any
    Object.keys(zmKeymap).forEach((key: string) => {
      if (item[zmKeymap[key]] || item[zmKeymap[key]] == 0) {
        // @ts-ignore
        zm[key] = item[zmKeymap[key]]
      }
      delete item[zmKeymap[key]]
    })
    if (Object.keys(zm).length) {
      list.push({
        ...zm,
        ...item
      })
    }
  }
  if (list.length) {
    result[key] = list
  }

  return result
}

export const formatedDataUtil = {
  collectingDistrictDataList: (data: any) => formatedData('ZM', data),
  collectingResponsibleDataList: (data: any) => formatedData('ZRZ', data)
}

export const formatedDataToFormUtil = {
  collectingDistrictDataList: (data: any) => formatedDataToForm('ZM', data),
  collectingResponsibleDataList: (data: any) => formatedDataToForm('ZRZ', data)
}
